package be.android.forap.broadcastreceiver;

import java.io.IOException;
import java.security.NoSuchProviderException;
import java.util.Scanner;

import org.bouncycastle.openpgp.PGPException;

import be.android.forap.Constants;
import be.android.forap.R;
import be.android.forap.crypto.PatternUtil;
import be.android.forap.gui.DownloadActivity;
import be.android.forap.gui.MainActivity;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsSendReceiver extends BroadcastReceiver {

	private static final String ACTION_SEND = "SMS_SEND";
	private static final String ACTION_DELIVERED = "SMS_DELIVERED";
	private static final String ACTION_RECIEVED = "android.provider.Telephony.SMS_RECEIVED";

	private String messagefrom= "";
	private String messagebody = "";

	public void onReceive(Context c, Intent intent) {
		if (intent != null && intent.getAction() != null && ACTION_SEND.compareToIgnoreCase(intent.getAction()) == 0) {
			switch (getResultCode())
			{
			case Activity.RESULT_OK:
				Toast.makeText(c, "SMS send", Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
				Toast.makeText(c, "Generic failure", Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_NO_SERVICE:
				Toast.makeText(c, "No service", Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_NULL_PDU:
				Toast.makeText(c, "Null PDU", Toast.LENGTH_SHORT).show();
				break;
			case SmsManager.RESULT_ERROR_RADIO_OFF:
				Toast.makeText(c, "Radio off", Toast.LENGTH_SHORT).show();
				break;
			}
		}
		if (intent != null && intent.getAction() != null && ACTION_DELIVERED.compareToIgnoreCase(intent.getAction()) == 0) {
			switch (getResultCode())
			{
			case Activity.RESULT_OK:
				Toast.makeText(c, "SMS delivered", Toast.LENGTH_SHORT).show();
				//showNotification(c,"Key succesfully send","forAP","The key was succesfully send.");

				break;
			case Activity.RESULT_CANCELED:
				Toast.makeText(c, "SMS not delivered", Toast.LENGTH_SHORT).show();
				break;					    
			}
		}
		if (intent != null && intent.getAction() != null && ACTION_RECIEVED.compareToIgnoreCase(intent.getAction()) == 0) {
			Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
			SmsMessage[] messages = new SmsMessage[pduArray.length];
			String number = "";
			for (int i = 0; i < pduArray.length; i++) {
				messages[i] = SmsMessage.createFromPdu((byte[])pduArray[i]);
				number = messages[i].getOriginatingAddress();
				messagebody = messagebody + messages[i].getMessageBody();
				Log.d("My SMSReceiver", "From: " + messagefrom);
				Log.d("My SMSReceiver", "Msg: " + messagebody);					
			}

			if(isEncryptedExchangeMessage(messagebody)){
				handleEncryptedMessageExchange(number, c);
			}
			if(isKeyExchangeMessage(messagebody)){
				handleKeyExchange(number, c);
			}
			if(isEncryptedMessage(messagebody)){
				handleEncryptedMessage(number,c);
			}
		}
	}



	private void handleEncryptedMessageExchange(String number, Context c) {
		Scanner scanner = new Scanner(messagebody);
		boolean matching = false;
		while (!matching && scanner.hasNextLine()) {
			String line = scanner.nextLine();
			// process the line
			matching =line.matches("http://.*");
			if(matching){
				Intent download = new Intent(c, DownloadActivity.class);

				download.putExtra(DownloadActivity.SENDER_DL_LINK, number);
				Log.d("n",number);

				download.putExtra(DownloadActivity.DOWNLOAD_PATH, line);
				String nextline = scanner.nextLine();
				download.putExtra(DownloadActivity.DOWNLOAD_SIZE, nextline);

				download.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

				showKeyExchangeNotification(c, "Encrypted Message recieved", "forAp", "Click to decrypt.",download);
			}
		}

	}

	private void handleEncryptedMessage(String number, Context c) {
		Intent openDecrypt = new Intent(c, MainActivity.class);
		openDecrypt.setAction(Constants.DECRYPT_SMS_ACTION);
		openDecrypt.putExtra(MainActivity.CONTENT_SMS, messagebody);
		openDecrypt.putExtra(MainActivity.SMS_NUMBER, number);
		openDecrypt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		showEncryptedMessageNotification(c, "Encrypted Message recieved", "forAp", "Click to decrypt.",openDecrypt);
	}



	private void handleKeyExchange(String number, Context c) {
		Log.d("My SMSReceiver","message is keyexchange");
		Scanner scanner = new Scanner(messagebody);
		boolean matching = false;
		while (!matching && scanner.hasNextLine()) {
			String line = scanner.nextLine();
			// process the line
			matching =line.matches("http://.*");
			if(matching){
				Intent download = new Intent(c, DownloadActivity.class);

				download.putExtra(DownloadActivity.SENDER_DL_LINK, number);
				Log.d("n",number);

				download.putExtra(DownloadActivity.DOWNLOAD_PATH, line);
				String nextline = scanner.nextLine();
				download.putExtra(DownloadActivity.DOWNLOAD_SIZE, nextline);
				String lastline = scanner.nextLine();
				download.putExtra(DownloadActivity.DOWNLOAD_DIGEST, lastline);

				download.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

				showKeyExchangeNotification(c, "Key Exchange Message recieved", "forAp", "Click to import the key.",download);
			}
		}
	}

	private boolean isEncryptedMessage(String text) {
		return PatternUtil.matchPGPBlock(text, PatternUtil.PGP_MESSAGE);
		/*Log.d("My SMSReceiver","testing if message is pgp" + text);
		Scanner scanner = new Scanner(text);
		boolean matching = false;
		while (!matching && scanner.hasNextLine()) {
		  String line = scanner.nextLine();
		  // process the line
		  matching =line.matches("-----BEGIN PGP MESSAGE-----");
		}
		return matching;*/
	}

	private boolean isEncryptedExchangeMessage(String text) {
		Scanner scanner = new Scanner(text);
		boolean matching = false;
		while (!matching && scanner.hasNextLine()) {
			String line = scanner.nextLine();
			// process the line
			matching =line.matches("----FORAP MESSAGE EXCHANGE----");
		}
		return matching;
	}

	private boolean isKeyExchangeMessage(String text) {
		Scanner scanner = new Scanner(text);
		boolean matching = false;
		while (!matching && scanner.hasNextLine()) {
			String line = scanner.nextLine();
			// process the line
			matching =line.matches("----FORAP KEY EXCHANGE----");
		}
		return matching;
	}

	private void addSmsToSentBox(String message, String phoneNumber, Context c) {
		ContentValues values = new ContentValues();
		values.put("address", phoneNumber);
		values.put("date", System.currentTimeMillis());
		values.put("body", message);
		c.getContentResolver().insert(Uri.parse("content://sms"), values);
	}


	public static final int NOTIFICATION_SMS_DELIVERED = 1;

	private void showEncryptedMessageNotification(Context context,String tickerText,String contentTitle,String contentText, Intent launcher){
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher_lock, tickerText, System.currentTimeMillis());
		//notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,  launcher, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(NOTIFICATION_SMS_DELIVERED, notification);
	}

	private void showKeyExchangeNotification(Context context,String tickerText,String contentTitle,String contentText, Intent launcher){
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher_lock, tickerText, System.currentTimeMillis());
		//notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,  launcher, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(NOTIFICATION_SMS_DELIVERED, notification);
	}
}
